import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras import utils
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape)
x_train = tf.reshape(x_train,(x_train.shape[0], x_train.shape[1],x_train.shape[2],1))
x_test = tf.reshape(x_test, (x_test.shape[0], x_test.shape[1],x_test.shape[2],1))
net=tf.keras.models.Sequential([
    # 卷积层：6个5*5的卷积 sigmoid
    keras.layers.Conv2D(filters=6, kernel_size=5,
                           activation="sigmoid", input_shape=(28, 28, 1)),
    # max pooling
    keras.layers.MaxPool2D(pool_size=2, strides=2),
    # 卷积层：16 5*5 sigmoid
    keras.layers.Conv2D(filters=16, kernel_size=5, activation="sigmoid"),
    # max pooling
    keras.layers.MaxPool2D(pool_size=2, strides=2),
    # 维度调整
    keras.layers.Flatten(),
    # 全连接层，sigmoid
    keras.layers.Dense(120, activation="sigmoid"),
    # 全连接层，sigmoid
    keras.layers.Dense(84, activation="sigmoid"),
    # 输出层 softmax
    keras.layers.Dense(10, activation="softmax")
])
print(net.summary())
utils.plot_model(net, to_file='CNN.png', show_shapes=True)
net.compile(optimizer=keras.optimizers.SGD(learning_rate=0.9), loss=keras.losses.sparse_categorical_crossentropy, metrics=["accuracy"])
net.fit(x_train, y_train, epochs=10, batch_size=128,verbose=1)
print(net.evaluate(x_test, y_test,verbose=1))